<template>
  <view v-if="visible" class="record-selection-modal">
    <view class="modal-overlay" @click="closeModal"></view>
    <view class="modal-content">
      <view class="modal-header">
        <text class="modal-title">{{ title }}</text>
        <text class="modal-close" @click="closeModal">×</text>
      </view>
      <view class="modal-body">
        <view class="record-count">共找到 {{ records.length }} 条记录</view>
        <scroll-view scroll-y class="record-table">
          <view class="table-header">
            <view class="header-cell" @tap="toggleAllRecords">
              <text v-if="isAllSelected" class="check-icon">✓</text>
              <text v-else class="uncheck-icon">○</text>
            </view>
            <view class="header-cell">批次号</view>
            <view class="header-cell">钢种</view>
            <view class="header-cell">规格</view>
            <view class="header-cell">业务日期</view>
            <view class="header-cell">退火入炉时间</view>
            <view class="header-cell">退火出炉时间</view>
          </view>
          <view
            class="table-row"
            v-for="record in records"
            :key="record.id"
            :class="{ selected: selectedIds.includes(record.id) }"
          >
            <view class="row-cell checkbox-cell" @tap="toggleRecord(record.id)">
              <text v-if="selectedIds.includes(record.id)" class="check-icon"
                >✓</text
              >
              <text v-else class="uncheck-icon">○</text>
            </view>
            <view class="row-cell">{{ record.batchNo }}</view>
            <view class="row-cell">{{ record.steelGradeName }}</view>
            <view class="row-cell">{{ record.prodSpec }}</view>
            <view class="row-cell">{{
              dateHelperApi.formateTime(record.ywDate)
            }}</view>
            <view class="row-cell">{{
              record.reserveVarchar1
                ? dateHelperApi.formateTime(record.reserveVarchar1)
                : ""
            }}</view>
            <view class="row-cell">{{
              record.reserveVarchar2
                ? dateHelperApi.formateTime(record.reserveVarchar2)
                : ""
            }}</view>
          </view>
        </scroll-view>
      </view>
      <view class="modal-footer">
        <button class="btn-cancel" @click="closeModal">取消</button>
        <button
          class="btn-confirm"
          @click="confirmSelection"
          :disabled="selectedIds.length === 0"
        >
          确定
        </button>
      </view>
    </view>
  </view>
</template>

<script>
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";

export default {
  name: "RecordSelectionModal",

  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "选择记录",
    },
    records: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      selectedIds: [], // 选中的记录ID数组
    };
  },

  computed: {
    // 是否全选
    isAllSelected() {
      return (
        this.records.length > 0 &&
        this.selectedIds.length === this.records.length
      );
    },
    dateHelperApi() {
      return dateHelperApi;
    },
  },

  watch: {
    // 当显示状态改变时重置选择
    visible(newVal) {
      if (newVal) {
        // 默认全选所有记录
        this.selectedIds = this.records.map((record) => record.id);
      } else {
        // 弹窗关闭时清空选择
        this.selectedIds = [];
      }
    },
    // 当记录数据变化时，如果是首次显示则全选
    records: {
      handler(newRecords) {
        if (
          this.visible &&
          newRecords.length > 0 &&
          this.selectedIds.length === 0
        ) {
          this.selectedIds = newRecords.map((record) => record.id);
        }
      },
      immediate: true,
    },
  },

  methods: {
    // 切换单个记录选择状态
    toggleRecord(recordId) {
      // 阻止事件冒泡
      event && event.stopPropagation && event.stopPropagation();

      const index = this.selectedIds.indexOf(recordId);
      if (index > -1) {
        this.selectedIds.splice(index, 1);
      } else {
        this.selectedIds.push(recordId);
      }
    },

    // 全选/取消全选
    toggleAllRecords() {
      // 阻止事件冒泡
      event && event.stopPropagation && event.stopPropagation();

      if (this.isAllSelected) {
        this.selectedIds = [];
      } else {
        this.selectedIds = this.records.map((record) => record.id);
      }
    },

    // 关闭弹窗
    closeModal() {
      this.selectedIds = [];
      this.$emit("close");
    },

    // 确认选择并执行更新
    async confirmSelection() {
      if (this.selectedIds.length === 0) {
        uni.showToast({
          title: "请至少选择一条记录",
          icon: "none",
        });
        return;
      }

      // 获取选中的完整记录数据
      const selectedRecords = this.records.filter((record) =>
        this.selectedIds.includes(record.id)
      );

      try {
        // 显示加载提示
        uni.showLoading({
          title: "正在更新...",
        });

        // 触发自定义事件，父组件处理更新逻辑
        // 注意：不在这里关闭弹窗，让父组件来控制关闭时机
        this.$emit("confirm", selectedRecords);
      } catch (error) {
        console.error("更新失败:", error);
        uni.showToast({
          title: "更新失败，请重试",
          icon: "none",
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 格式化业务日期
    formatBusinessDate(dateTimeStr) {
      if (!dateTimeStr) return "-";
      try {
        // 如果是完整的日期时间格式，只显示日期部分
        if (dateTimeStr.includes(" ")) {
          return dateTimeStr.split(" ")[0];
        }
        return formatDate(dateTimeStr);
      } catch (error) {
        console.error("日期格式化失败:", error);
        return dateTimeStr || "-";
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.record-selection-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  position: relative;
  background-color: white;
  border-radius: 12px;
  width: 95%;
  max-width: 900px;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fafafa;

  .modal-title {
    font-size: 20px;
    font-weight: 600;
    color: #333;
  }

  .modal-close {
    font-size: 28px;
    color: #999;
    cursor: pointer;
    padding: 4px 8px;
    transition: color 0.3s;

    &:hover {
      color: #666;
    }
  }
}

.modal-body {
  flex: 1;
  padding: 24px;
  overflow: hidden;

  .record-count {
    margin-bottom: 20px;
    font-size: 16px;
    color: #666;
    font-weight: 500;
  }

  .record-table {
    max-height: 55vh;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    overflow: hidden;
    background-color: white;

    .table-header {
      display: flex;
      background-color: #f8f9fa;
      border-bottom: 1px solid #e8e8e8;
      position: sticky;
      top: 0;
      z-index: 10;

      .header-cell {
        flex: 1;
        padding: 16px 12px;
        font-size: 15px;
        font-weight: 600;
        color: #495057;
        text-align: center;
        border-right: 1px solid #e8e8e8;
        display: flex;
        align-items: center;
        justify-content: center;

        &:first-child {
          flex: 0 0 70px;
        }

        &:last-child {
          border-right: none;
        }
      }
    }

    .table-row {
      display: flex;
      border-bottom: 1px solid #f0f0f0;
      transition: all 0.2s;
      cursor: pointer;

      &:hover {
        background-color: #f8f9fa;
      }

      &:last-child {
        border-bottom: none;
      }

      &.selected {
        background-color: #e3f2fd;
      }

      .row-cell {
        flex: 1;
        padding: 16px 12px;
        font-size: 14px;
        color: #495057;
        text-align: center;
        border-right: 1px solid #f0f0f0;
        display: flex;
        align-items: center;
        justify-content: center;
        min-height: 60px;

        &:first-child {
          flex: 0 0 70px;
        }

        &:last-child {
          border-right: none;
        }

        // 特殊样式处理选择列
        &.checkbox-cell {
          cursor: pointer;
          z-index: 10;
          position: relative;
        }

        .time-info {
          display: flex;
          flex-direction: column;
          gap: 4px;

          .time-item {
            font-size: 12px;
            color: #6c757d;
            line-height: 1.3;
          }
        }

        .no-time {
          color: #adb5bd;
          font-size: 13px;
        }
      }
    }
  }
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 20px 24px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;

  .btn-cancel {
    padding: 10px 20px;
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    background-color: white;
    color: #666;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      border-color: #40a9ff;
      color: #40a9ff;
    }
  }

  .btn-confirm {
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    background-color: #1890ff;
    color: white;
    font-size: 15px;
    cursor: pointer;
    transition: background-color 0.3s;
    min-width: 120px;

    &:hover:not(:disabled) {
      background-color: #40a9ff;
    }

    &:disabled {
      background-color: #d9d9d9;
      cursor: not-allowed;
      opacity: 0.6;
    }
  }
}

// 添加选择图标样式
.check-icon {
  color: #4caf50;
  font-size: 28rpx;
  font-weight: bold;
}

.uncheck-icon {
  color: #ccc;
  font-size: 28rpx;
}
</style>
